package com.learn.netty.nio.groupchat;


import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * 群聊服务器 客户端
 */
@Slf4j
public class GroupSystemClient {

    private Selector selector;

    private SocketChannel socketChannel;

    private static final String HOST = "127.0.0.1";

    private static final int PORT = 6669;

    private static String USERNAME;

    public GroupSystemClient() {
        try {
            selector = Selector.open();
            socketChannel = SocketChannel.open(new InetSocketAddress(HOST, PORT));
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_READ);
            USERNAME = socketChannel.getLocalAddress().toString().substring(1);
            log.info("{} 上线了...", USERNAME);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

    }

    /**
     * 读取消息
     * @throws Exception
     */
    private void readInfo() throws Exception {
        while (true) {
            int events = selector.select();
            if (events > 0) {
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    if (selectionKey.isReadable()) {
                        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        int read = socketChannel.read(byteBuffer);
                        if (read > 0) {
                            log.info("收到消息：{}", new String(byteBuffer.array()));
                        }
                    }

                    iterator.remove();
                }
            }

        }
    }

    /**
     * 发送消息
     * @param msg
     * @throws IOException
     */
    private void sendInfo(String msg) throws IOException {
        ByteBuffer byteBuffer = ByteBuffer.wrap(msg.getBytes());
        socketChannel.write(byteBuffer);
    }

    public static void main(String[] args) throws IOException {
        GroupSystemClient groupSystemClient = new GroupSystemClient();

        new Thread(() -> {
            try {
                groupSystemClient.readInfo();
            } catch (Exception e) {
                log.error(e.getMessage(),e);
            }
        }).start();

        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            groupSystemClient.sendInfo(scanner.nextLine());
        }
    }

}
